package com.baibei.order.list;


import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.baibei.model.BalanceInfo;
import com.baibei.model.OrderInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.module.RechargeHelper;
import com.baibei.order.R;
import com.baibei.order.R2;
import com.baibei.ui.AppUI;
import com.baibei.widget.PriceTextView;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页订单界面
 * shenminjie  2017-08-08
 */
public class IndexOrderFragment extends BasicFragment implements IndexOrderContract.IndexOrderView, IndexOrderAdapter.OnItemSelectListener {

    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.tv_income)
    PriceTextView mTvIncome;
    @BindView(R2.id.layout_header)
    CoordinatorLayout mLayoutHeader;
    @BindView(R2.id.layout_appbarlayout)
    AppBarLayout mLayoutAppbarlayout;
    @BindView(R2.id.tv_last_balance)
    TextView mTvLastBalance;

    private IndexOrderAdapter mAdapter;
    private IndexOrderContract.Presenter mPresenter;


    public IndexOrderFragment() {
    }

    public static IndexOrderFragment newInstance() {
        IndexOrderFragment fragment = new IndexOrderFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(IndexOrderContract.Presenter.class);
        EventBus.getDefault().register(this);
    }


    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_index_order;
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new IndexOrderAdapter(this);
        mLayoutAppbarlayout.setExpanded(true);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        //开始加载数据
        if (SessionManager.getDefault().isLogin()) {
            mPresenter.start();
        }

        mPresenter.registerQuotation();
    }

    @Override
    public void onStop() {
        super.onStop();
        mPresenter.unregisterQuotation();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //碎片管理，左右切换刷新数据
        if (isVisibleToUser && SessionManager.getDefault().isLogin() && mPresenter != null) {
            mPresenter.start();
        }
    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onRefreshCompeted() {

    }

    @Override
    public void onLoadOrderList(List<OrderInfo> infos) {
        //刷新数据比较
        mAdapter.setOrderList(infos);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadFailed(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void updateMyIncome(List<OrderInfo> infos) {
        double income = 0;
        for (OrderInfo info : infos) {
            income = income + info.getPrifitDifferent();
        }
        //4舍五入两位
        BigDecimal b = new BigDecimal(income);
        income = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        mTvIncome.setPrice(income);
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void onLoadBalanceFailed(String msg) {
//        AppUI.failed(getContext(), msg);
        mTvLastBalance.setText(String.format(getString(R.string.available_balance), "--"));
    }

    @Override
    public void onLoadBalanceInfo(BalanceInfo balanceInfo) {
        mTvLastBalance.setText(String.format(getString(R.string.available_balance), String.valueOf(Rx.formatPrice(balanceInfo.getBalance()))));
    }

    @Override
    public void onUnsubscribeTimeout() {
        hideLoading();
        AppUI.failed(getContext(), "退订超时");
    }

    @Override
    public void onUnsubscribeSuccess(String msg) {
        AppUI.success(getContext(), msg);
    }

    @Override
    public void onItemSelectListener(View view, OrderInfo orderInfo, int position) {
        //点击跳转详情
        AppRouter.routeToOrderDetail(getContext(), orderInfo);
    }

    @Override
    public void onUnsubscribeBtnClickListener(View view, final OrderInfo info, int position) {
        new DialogBuilder(getContext()).setMessage(R.string.dialog_title_unsubscribe).positiveButtonClickListener(new IAppDialogClickListener() {
            @Override
            public void onClick(IAppDialog iAppDialog, int i) {
                iAppDialog.dismiss();
                mPresenter.unsubscribeOrder(info.getOrderid(), info.getArea());
            }
        }).negativeButtonClickListener(new IAppDialogClickListener() {
            @Override
            public void onClick(IAppDialog iAppDialog, int i) {
                iAppDialog.dismiss();
            }
        }).show();
    }

    @Override
    public void onReload() {
        mPresenter.start();
    }

    @OnClick(R2.id.layout_to_recharge)
    public void onViewClicked() {
        RechargeHelper.toRecharge(getActivity(),this);
    }

    @Subscribe
    public void onEvent(LoginEvent event) {
        // 清空登录状态
    }
}
